#include <header.h>

int main(){
    char *port = "8080";
    char *ip = "192.168.233.128";

    int socket_fd = socket(AF_INET,SOCK_STREAM,0);

    int reuse = 1;
    setsockopt(socket_fd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));


    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(port));
    sockaddr.sin_addr.s_addr = inet_addr(ip);

    bind(socket_fd,(struct sockaddr*)&sockaddr,sizeof(sockaddr));
    listen(socket_fd,10);

    int list[100] = {0};
    int size = 0;

    fd_set base_set;
    FD_ZERO(&base_set);
    FD_SET(socket_fd,&base_set);

    while(1){
        fd_set set;
        memcpy(&set,&base_set,sizeof(base_set));


        select(100,&set,NULL,NULL,NULL);

        if(FD_ISSET(socket_fd,&set)){
            int nat_fd = accept(socket_fd,NULL,NULL);
            FD_SET(nat_fd,&base_set);
            list[size] = nat_fd;
            size ++;
        }

        for(int i = 0;i < size;i++){
            if(FD_ISSET(list[i],&set)){
                char buf[100] = {0};
                ssize_t ret = recv(list[i],buf,sizeof(buf),0);
                if(ret == 0){
                    FD_CLR(list[i],&base_set);
                    for(int j = i;j < size;j++){
                        list[j] = list[j + 1];
                    }
                    size--;
                    i--;
                    continue;
                }

                for(int k = 0;k < size;k++){
                    if(k != i){
                        send(list[k],buf,sizeof(buf),0);
                    }

                }
            }
        }

    }
    close(socket_fd);
    return 0;
}
